package com.ljj.gulimall.product.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljj.common.utils.PageUtils;
import com.ljj.common.utils.Query;
import com.ljj.gulimall.product.dao.CategoryDao;
import com.ljj.gulimall.product.entity.CategoryEntity;
import com.ljj.gulimall.product.service.CategoryService;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<CategoryEntity> page = this.page(new Query<CategoryEntity>().getPage(params),
				new QueryWrapper<CategoryEntity>());

		return new PageUtils(page);
	}

	@Override
	public List<CategoryEntity> listTree() {
		// TODO Auto-generated method stub
		// 1.查出所有分类数据
		List<CategoryEntity> list = baseMapper.selectList(null);
		// 2.组装父子关系

		// 2.1 先把一级分类找出来，parentId = 0
		List<CategoryEntity> level1Menus = list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
				.map(menu -> {
					menu.setChildren(getChildren(menu, list));
					return menu;
				}).sorted((menu1, menu2) -> {
					return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
				}).collect(Collectors.toList());

		return level1Menus;
	}

	/**
	 * 递归查找并设置所有菜单的子菜单
	 * @param parent 父菜单
	 * @param all 所有菜单
	 * @return 所有子菜单
	 */
	private List<CategoryEntity> getChildren(CategoryEntity parent, List<CategoryEntity> all) {
		List<CategoryEntity> children = all.stream().filter(categpryEntity -> {
			return categpryEntity.getParentCid() == parent.getCatId();
		}).map(menu -> {
			menu.setChildren(getChildren(menu, all));
			return menu;
		}).sorted((menu1, menu2) -> {
			return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
		}).collect(Collectors.toList());
		return children;
	}

	@Override
	public void removeMenusByIds(List<Long> asList) {
		// TODO 1、检查是否被引用
		
		// 2、删除菜单
		baseMapper.deleteBatchIds(asList);
	}

}